package com.hc.vo;


import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.ibatis.javassist.NotFoundException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

public class QRCodeUtil {
    public static void write(String writepath,String filepath) throws WriterException, IOException {
        //2.通过zxing生成二维码 (保存到本地图片， 支持以data url 的形式体现)
        //创建QRCodeWriter对象
        QRCodeWriter writer = new QRCodeWriter();
        //生成的图片基本配置
        /*
        参数
        1.二维码信息
        2.图片类型
        3.图片宽度
        4.图片长度
        */

        BitMatrix bt = writer.encode(writepath, BarcodeFormat.QR_CODE, 200, 200);
        //保存到本地
        Path path = new File(filepath).toPath();
        MatrixToImageWriter.writeToPath(bt,"png",path);
    }
    public static String parse(String filepath) throws IOException {
        File file = new File(filepath);
        //将图片加载缓存中
        BufferedImage bufferedImage = ImageIO.read(file);
        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);

        HashMap<DecodeHintType, Object> hits = new HashMap<DecodeHintType, Object>();
        hits.put(DecodeHintType.CHARACTER_SET, "UTF-8");

        Result  result = null;
        try {
            result = new MultiFormatReader().decode(bitmap,hits);
        } catch (com.google.zxing.NotFoundException e) {
            e.printStackTrace();
        }
        return result.toString();

    }

}
